package com.hzdp.handles.rival.processors;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * Created by leo on 15/11/28.
 * <p/>
 * 天猫美妆
 */
public class TmallProcessor implements PageProcessor {

    static final String START_URL = "https://detail.tmall.com/item.htm?spm=a220m.1000858.1000725.232.ESS9G9&id=523176098783&skuId=3116381734641&areaId=310100&cat_id=50026502&rn=4effe4184f342464115bac171572b5d0&user_id=1759430182&is_b=1";
    static final String CONTENT_URL_PATTERN = "https://detail\\.tmall\\.com/item\\.htm\\?.+";

    static final String LIST_URL_PATTERN = "https://list\\.tmall\\.com/search\\_product\\.htm\\?cat.+";

    private Site site = Site.me()
            //.setDomain(".tmall.com")
            //.setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31")
            .setRetryTimes(3).setSleepTime(100);

    @Override
    public void process(Page page) {
//        page.putField("sourceUrl", page.getUrl().regex("https://github\\.com/(\\w+)/.*").toString());
//        page.putField("name", page.getHtml().xpath("//h1[@class='entry-title public']/strong/a/text()").toString());
////        if (page.getResultItems().get("name") == null) {
////            //skip this page
////            page.setSkip(true);
////        }
//        page.putField("imgUrlList", page.getHtml().xpath("//div[@id='readme']/tidyText()"));
//        page.putField("descList", page.getHtml().xpath("//div[@id='readme']/tidyText()"));
        if (page.getUrl().regex(CONTENT_URL_PATTERN).match()) {
            page.putField("sourceUrl", page.getUrl().regex(CONTENT_URL_PATTERN).toString());
            page.putField("name", page.getHtml().css(".tb-detail-hd").$("h1", "text").toString());
            page.putField("imgUrls", page.getHtml().xpath("//ul[@id='J_UlThumb']/li/a").$("img", "src").all());
        } else {
            page.addTargetRequests(page.getHtml().links().regex(LIST_URL_PATTERN).all());
            page.addTargetRequests(page.getHtml().links().regex(CONTENT_URL_PATTERN).all());
        }

    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new TmallProcessor()).addUrl(START_URL).addPipeline(new JsonFilePipeline("/Users/lyp/webmagic")).run();
    }
}
